package com.jinzhi.jzweb.controller;


import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2021-07-23 10:29:39 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/classesExaminationSubmit")
public class ClassesExaminationSubmitController extends BaseController {
	@Autowired
	private ClassesExaminationSubmitService classesExaminationSubmitService;
    @Autowired
    private ClassesExaminationPaperService classesExaminationPaperService;
    @Autowired
    private UserService userService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private MajorItemBankService majorItemBankService;
    @Autowired
    private ClassesExaminationSubmitAnswersService classesExaminationSubmitAnswersService;

	
	@GetMapping()
	@RequiresPermissions("jzweb:classesExaminationSubmit:classesExaminationSubmit")
	String ClassesExaminationSubmit(){
	    return "jzweb/classesExaminationSubmit/classesExaminationSubmit";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:classesExaminationSubmit:classesExaminationSubmit")
	public Result<Page<ClassesExaminationSubmitDO>> list(ClassesExaminationSubmitDO CES){
		// 查询列表数据
        Wrapper<ClassesExaminationSubmitDO> wrapper = new EntityWrapper<ClassesExaminationSubmitDO>().orderBy("id", false);
        if(CES.getIsExamine()!=null && !CES.getIsExamine().equals("")){
            wrapper.eq("is_examine",CES.getIsExamine());
        }
        if(CES.getStatus()!=null && !CES.getStatus().equals("")){
            wrapper.eq("status",CES.getStatus());
        }
        if(CES.getPapersName()!=null && !CES.getPapersName().equals("")){
            Wrapper<ClassesExaminationPaperDO> CEPwrapper = new EntityWrapper<ClassesExaminationPaperDO>().orderBy("id", false);
            CEPwrapper.eq("name",CES.getPapersName());
            // 查询列表数据
            List<ClassesExaminationPaperDO> CEPList = classesExaminationPaperService.selectList(CEPwrapper);
            String str = "";
            for (ClassesExaminationPaperDO CEP : CEPList){
                str = str + CEP.getId() + ",";
            }
            wrapper.and();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(str)){
                wrapper.in("classes_examination_paper_id",str.substring(0,str.length()-1));
            }else{
                wrapper.eq("classes_examination_paper_id",null);
            }
            Wrapper<UserDO> userWrapper = new EntityWrapper<UserDO>().like("name",CES.getUserName());
            List<UserDO> userDOS = userService.selectList(userWrapper);
            str = "";
            for (UserDO userDO : userDOS){
                str = str + userDO.getId() + ",";
            }
            wrapper.and();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(str)){
                wrapper.in("stu_id",str.substring(0,str.length()-1));
            }else{
                wrapper.eq("stu_id",null);
            }

        }
        // 查询列表数据
        Page<ClassesExaminationSubmitDO> page = classesExaminationSubmitService.selectPage(getPage(ClassesExaminationSubmitDO.class),
                wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			ClassesExaminationSubmitDO obj = (ClassesExaminationSubmitDO) page.getRecords().get(i);
            ClassesExaminationPaperDO CEP = this.classesExaminationPaperService.selectById(obj.getClassesExaminationPaperId());

            UserDO userDO = userService.selectById(obj.getStuId());
            if(userDO!=null && userDO.getName()!=null) {
                if (userDO.getName() != null) {
                    obj.setUserName(userDO.getName());
                } else {
                    obj.setUserName("");
                }
            }else {
                if (userDO.getUsername() != null) {
                    obj.setUserName(userDO.getUsername());
                } else {
                    obj.setUserName("");
                }
            }
            //班级名称
            StudentClassesDO studentClassesDO = classesService.selectById(CEP.getClassId());
            if(studentClassesDO!=null && studentClassesDO.getName()!=null){
                obj.setStudentClassName(studentClassesDO.getName());
            }else {
                obj.setStudentClassName("");
            }

            if(CEP.getName()!=null){
                obj.setPapersName(CEP.getName());
            }else {
                obj.setPapersName("");
            }
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:classesExaminationSubmit:add")
	String add(){
	    return "jzweb/classesExaminationSubmit/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:classesExaminationSubmit:edit")
	String edit(@PathVariable("id") Long id,Model model){
		ClassesExaminationSubmitDO classesExaminationSubmit = classesExaminationSubmitService.selectById(id);
		model.addAttribute("classesExaminationSubmit", classesExaminationSubmit);
	    return "jzweb/classesExaminationSubmit/edit";
	}
	
	@Log("添加")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:classesExaminationSubmit:add")
	public Result<String> save( ClassesExaminationSubmitDO classesExaminationSubmit){
		classesExaminationSubmitService.insert(classesExaminationSubmit);
        return Result.ok();
	}
	
	@Log("修改")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:classesExaminationSubmit:edit")
	public Result<String>  update( ClassesExaminationSubmitDO classesExaminationSubmit){
		boolean update = classesExaminationSubmitService.updateById(classesExaminationSubmit);
		return update ? Result.ok() : Result.fail();
	}


    @GetMapping("/info/{id}")
    @RequiresPermissions("jzweb:classesExaminationSubmit:classesExaminationSubmit")
    String info(@PathVariable("id") Long id, Model model) {

        Map map = new HashMap();
        List<Map> itmsMap = new ArrayList<>();
        List<Map> itmsType4Map = new ArrayList<>();

        boolean flag = false;
        Long submitId = 0L;
        Long paperId = 0L;
        double score = 0;
        ClassesExaminationSubmitDO submitDOS = classesExaminationSubmitService.selectById(id);
        if (submitDOS!=null) {
            flag = true;
            submitId = submitDOS.getId();
            map.put("submitId", submitId);
            map.put("submitStatus", submitDOS.getStatus());
            map.put("isExamine", submitDOS.getIsExamine());
            paperId = submitDOS.getClassesExaminationPaperId();

            UserDO userDO = userService.selectById(submitDOS.getStuId());
            if(userDO!=null && userDO.getName()!=null) {
                if (userDO.getName() != null) {
                    map.put("stuName", userDO.getName());
                } else {
                    map.put("stuName", "");
                }
            }else {
                if (userDO.getUsername() != null) {
                    map.put("stuName", userDO.getUsername());
                } else {
                    map.put("stuName", "");
                }
            }

        } else {
            map.put("submitId", "");
            map.put("submitStatus", "");
            map.put("stuName", "");
        }

        ClassesExaminationPaperDO CEP = classesExaminationPaperService.selectById(paperId);
        if(CEP!=null) {
            if (CEP.getName() != null) {
                map.put("title", CEP.getName());
            } else {
                map.put("title", "");
            }
            map.put("id", id);
            //是否已截止
            Date sd1 = CEP.getEndTime();
            Date sd2 = new Date();

            if (sd2.before(sd1)) {
                map.put("isOver", 0);
            } else {
                map.put("isOver", 1);
            }
            //班级名称
            StudentClassesDO studentClassesDO = classesService.selectById(CEP.getClassId());
            if(studentClassesDO!=null && studentClassesDO.getName()!=null){
                map.put("studentClassName", studentClassesDO.getName());
            }else {
                map.put("studentClassName", "");
            }


            if (CEP.getItems() != null) {
                // System.out.println("papersDeploymentDO.getItems():"+papersDeploymentDO.getItems());
                String[] itemsStr = CEP.getItems().split(",");
                if (itemsStr.length > 0) {
                    for (int a = 0; a < itemsStr.length; a++) {
                        if (!itemsStr[a].equals("")) {
                            MajorItemBankDO ItemBankDO = this.majorItemBankService.selectById(Long.valueOf(itemsStr[a]));
                            //System.out.println("1111:"+ItemBankDO.getId());
                            if (ItemBankDO != null) {
                                if (ItemBankDO.getState() != 9) {//没有被删除
                                    Map obj = new HashMap();
                                    obj.put("id", ItemBankDO.getId());
                                    obj.put("topic_content", ItemBankDO.getTopicContent());
                                    obj.put("type", ItemBankDO.getType());
                                    obj.put("options", ItemBankDO.getOptions());
                                    obj.put("rightKey", ItemBankDO.getRightKey());
                                    obj.put("score", ItemBankDO.getScore());

                                    obj.put("resource_type", ItemBankDO.getResourceType());
                                    obj.put("resource_url", ItemBankDO.getResourceUrl());

                                    double getScore = 0;
                                    String answer_student = "";
                                    if (flag) {
                                        Wrapper<ClassesExaminationSubmitAnswersDO> answersDOWrapper = new EntityWrapper<ClassesExaminationSubmitAnswersDO>().orderBy("id", false);
                                        answersDOWrapper.eq("items_id", ItemBankDO.getId());
                                        answersDOWrapper.eq("submit_id", submitId);
                                        List<ClassesExaminationSubmitAnswersDO> answersDOS = classesExaminationSubmitAnswersService.selectList(answersDOWrapper);
                                        if (answersDOS.size() > 0) {
                                            answer_student = answersDOS.get(0).getAnswer();
                                            obj.put("answer", answersDOS.get(0).getAnswer());
                                            obj.put("getScore", answersDOS.get(0).getScore());
                                            getScore = answersDOS.get(0).getScore();
                                            score += answersDOS.get(0).getScore();
                                        } else {
                                            obj.put("answer", "");
                                            obj.put("getScore", "");
                                        }
                                    } else {
                                        obj.put("answer", "");
                                        obj.put("getScore", "");
                                    }
                                    if(getScore == ItemBankDO.getScore()){
                                        obj.put("yesOrNo", "正确");
                                    }else {
                                        obj.put("yesOrNo", "错误");
                                    }

                                    List<Map> childrenList = new ArrayList<>();
                                    if (ItemBankDO.getType() != 4 && ItemBankDO.getType() != 3) {
                                        if (ItemBankDO.getOptions() != null) {
                                            String[] optionsList = ItemBankDO.getOptions().split(";;");
                                            if (optionsList.length > 0) {
                                                for (int b = 0; b < optionsList.length; b++) {
                                                    Map childrenMap = new HashMap();
                                                    childrenMap.put("value", optionsList[b]);
                                                    if (ItemBankDO.getType() == 0 || ItemBankDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
                                                        if (optionsList[b].equals(answer_student)) {
                                                            childrenMap.put("selected", 1);
                                                        } else {
                                                            childrenMap.put("selected", 0);
                                                        }
                                                    } else if (ItemBankDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案
                                                        boolean isSelect = true;
                                                        if (answer_student == null || answer_student == "") {
                                                            isSelect = false;
                                                        } else {
                                                            String[] answer_studentList = answer_student.split(";;");
                                                            if (answer_studentList.length > 0) {
                                                                for (int n = 0; n < answer_studentList.length; n++) {
                                                                    if (optionsList[b].contains(answer_studentList[n])) {
                                                                        isSelect = false;
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                        }

                                                        if (isSelect) {
                                                            childrenMap.put("selected", 1);
                                                        } else {
                                                            childrenMap.put("selected", 0);
                                                        }
                                                    }
                                                    childrenList.add(childrenMap);
                                                }
                                            }
                                        }

                                    } else if (ItemBankDO.getType() == 3) {//填空
                                       /* int bankNum = ItemBankDO.getTopicContent().indexOf("__");
                                        obj.put("bankNum", bankNum);*/
                                        String[] topicList = ItemBankDO.getTopicContent().split("__");
                                        String[] answerList = answer_student.split(";;");
                                        if (topicList.length > 0) {
                                            for (int b = 0; b < topicList.length; b++) {
                                                Map childrenMap = new HashMap();
                                                childrenMap.put("topic", topicList[b]);
                                                if (answerList.length > 0) {
                                                    if (answerList.length > b && answerList[b] != null && !answerList[b].equals("")) {
                                                        childrenMap.put("value", answerList[b]);
                                                    } else {
                                                        childrenMap.put("value", "");
                                                    }
                                                } else {
                                                    childrenMap.put("value", "");
                                                }
                                                childrenList.add(childrenMap);
                                            }
                                        }
                                    }
                                    obj.put("childrenSize", childrenList.size());
                                    obj.put("children", childrenList);
                                    if(ItemBankDO.getType()==4) {
                                        itmsType4Map.add(obj);
                                    }else {
                                        itmsMap.add(obj);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            map.put("numStart", 0);
            map.put("id", id);
            map.put("score", score);
        }
        System.out.println("submitMap:"+map.toString());
        model.addAttribute("submitMap", map);
        model.addAttribute("itmsMap", itmsMap);
        model.addAttribute("itmsType4Map", itmsType4Map);
        model.addAttribute("itmsType4MapSize", itmsType4Map.size());
        return "jzweb/classesExaminationSubmit/info";
    }


    @Log("阅题")
    @ResponseBody
    @PostMapping("/submitClassesExaminationResult")
    @RequiresPermissions("jzweb:classesExaminationSubmit:add")
    public Result<String> submitClassesExaminationResult(String result, String type, String submitId){
        System.out.println("result:"+result);
        System.out.println("type:"+type);
        if(result == null ){
            return Result.fail("参数错误！");
        }
        if(result .equals("")){
            return Result.fail("参数错误！");
        }
        boolean flag = false;

        JSONArray array = JSONArray.parseArray(result);
        if(array!=null && array.size()>0){
            for(int a = 0; a<array.size(); a++){
                JSONObject obj = JSONArray.parseObject(array.get(a)+"");
                if(obj!=null && !obj.equals("")){
                    if(obj.get("id")!=null && !obj.get("id").toString().equals("")){
                        Wrapper<ClassesExaminationSubmitAnswersDO> answersDOWrapper = new EntityWrapper<ClassesExaminationSubmitAnswersDO>().orderBy("id", false);
                        answersDOWrapper.eq("items_id", Long.valueOf(obj.get("id").toString()));
                        answersDOWrapper.eq("submit_id", submitId);
                        List<ClassesExaminationSubmitAnswersDO> answersDOS = classesExaminationSubmitAnswersService.selectList(answersDOWrapper);
                        if(answersDOS.size()>0){
                            ClassesExaminationSubmitAnswersDO answersDO = classesExaminationSubmitAnswersService.selectById(answersDOS.get(0).getId());
                            answersDO.setScore(Double.valueOf(obj.get("value").toString()));
                            this.classesExaminationSubmitAnswersService.updateById(answersDO);
                        }
                    }
                }
            }
            System.out.println("submitId:"+submitId);
            if(type!=null && !type.equals("")) {
                if(type.equals("1")) {//已阅完题
                    ClassesExaminationSubmitDO submitDO = classesExaminationSubmitService.selectById(submitId);
                    if (submitDO != null) {
                        submitDO.setIsExamine(1);

                        //查询总得分，判断是否通过考试
                        Map map = new HashMap();
                        map.put("submit_id", submitId);
                        Double sumScore = classesExaminationSubmitAnswersService.selSumScore(map);
                        System.out.println("sumScore:------------------"+sumScore);
                        ClassesExaminationPaperDO paperDO = classesExaminationPaperService.selectById(submitDO.getClassesExaminationPaperId());
                        if(sumScore > paperDO.getPassMark()){
                            submitDO.setStatus(1);//通过
                        }

                        submitDO.setTotalScore(sumScore);//更新总分数

                        if (this.classesExaminationSubmitService.updateById(submitDO)) {
                            flag = true;
                        }
                    }
                }else {
                    flag = true;
                }
            }else {
                flag = true;
            }
        }
        if(flag) {
            return Result.ok();
        }else {
            return Result.fail("保存状态失败！");
        }
    }


    @Log("删除")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:classesExaminationSubmit:remove")
	public Result<String>  remove( Long id){
        Wrapper<ClassesExaminationSubmitAnswersDO> answersDOWrapper = new EntityWrapper<ClassesExaminationSubmitAnswersDO>().orderBy("id", false);
         answersDOWrapper.eq("submit_id", id);
        List<ClassesExaminationSubmitAnswersDO> answersDOS = classesExaminationSubmitAnswersService.selectList(answersDOWrapper);
        if(answersDOS.size()>0){
            for (ClassesExaminationSubmitAnswersDO CES:answersDOS){
                classesExaminationSubmitAnswersService.deleteById(CES.getId());
            }
        }
		classesExaminationSubmitService.deleteById(id);

        return Result.ok();
	}
	
	@Log("批量删除")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:classesExaminationSubmit:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
	    if(ids.length>0){
	        for (int a=0; a<ids.length; a++){
                Wrapper<ClassesExaminationSubmitAnswersDO> answersDOWrapper = new EntityWrapper<ClassesExaminationSubmitAnswersDO>().orderBy("id", false);
                answersDOWrapper.eq("submit_id", ids[a]);
                List<ClassesExaminationSubmitAnswersDO> answersDOS = classesExaminationSubmitAnswersService.selectList(answersDOWrapper);
                if(answersDOS.size()>0){
                    for (ClassesExaminationSubmitAnswersDO CES:answersDOS){
                        classesExaminationSubmitAnswersService.deleteById(CES.getId());
                    }
                }
            }
        }
		classesExaminationSubmitService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}


}
